#include "maininterface.h"
#include "ui_maininterface.h"
#include <QString>
#include <QIcon>
#include <QPushButton>
#include <QDebug>
#include <QLineEdit>
#include <QSqlQuery>
#include <QSqlError>
#include <QBuffer>
#include <QMessageBox>

struct WidgetPrivate
{
    QSqlDatabase db;    // qt数据库对象
};


MainInterface::MainInterface(QWidget *parent,NetworkManager *networkManager) :
    QWidget(parent),
    networkManager(networkManager),
    ui(new Ui::MainInterface),
    socket(new QTcpSocket(this))    // 初始化TCP套接字
{
    ui->setupUi(this);

    QIcon icon(":/icon/111.jpg");       // 设置程序图标
    setWindowIcon(icon);

    setWindowTitle("学生端登录界面");     // 设置窗口标题

    ui->lineEdit_ID->setPlaceholderText("请输入账号");
    ui->lineEdit_passwd->setPlaceholderText("请输入密码");

    ui->lineEdit_passwd->setEchoMode(QLineEdit::Password);  // 将密码的输入框回显密码模式

    socket = networkManager->getSocket();   // 初始化 socket

    // 登录按钮点击事件
    connect(ui->Register,&QPushButton::clicked,this,&MainInterface::onResButtonClicked);

    // 连接服务器响应的信号
    connect(socket,&QTcpSocket::readyRead,this,&MainInterface::readServerResponse);

}


MainInterface::~MainInterface()
{
    delete ui;
}

// 登录按钮点击的槽函数
void MainInterface::onResButtonClicked()
{
    // 获取ID和密码
    QString ID = ui->lineEdit_ID->text();
    QString passwd = ui->lineEdit_passwd->text();

    // 检查ID和密码是否为空
    if(ID.isEmpty() || passwd.isEmpty())
    {
        QMessageBox::warning(this,"Error","ID 和 passwd 不能为空!");
        return;
    }

    // 构造JSON数据
    QJsonObject jsonObj;
    jsonObj["type"] = REGIS;
    jsonObj["ID"] = ID;
    jsonObj["passwd"] = passwd;

    // 将json对象转换为字节数组
    QJsonDocument jsonDoc(jsonObj);
    QByteArray data = jsonDoc.toJson(QJsonDocument::Compact);

    // 发送数据到服务器
    size_t dataSize = data.size();
    socket->write((const char *)&dataSize,sizeof(size_t));  // 先发送包头
    socket->write(data);                                    // 再发送json数据(包体)

    emit ReginBtnClicked();     //  发送登录按钮点击信号
}

// 读取服务器响应
void MainInterface::readServerResponse()
{
    auto Content = socket->readAll();
    buffer.append(Content);
    while(buffer.size() > sizeof(size_t))
    {
        size_t size = 0;
        memcpy(&size,buffer.data(),sizeof (size_t));

        if(buffer.size() <size + sizeof(size_t))
        {
            break;
        }

        auto data = buffer.mid(sizeof(size_t),size);
        // json解析
        QJsonDocument doc = QJsonDocument::fromJson(data);
        QJsonObject jsonObj = doc.object();

       int type = jsonObj["type"].toInt();
       qDebug()<<"type what:"<<type;

       handle = GetHandlePtr(jsonObj["type"].toInt());
       qDebug()<<"what :"<<jsonObj["type"].toInt();
       handle->MFHandle(jsonObj,this);

       buffer.remove(0,size + sizeof(size_t));

    }
}

// 登录成功
void REGISSUCCESS::MFHandle(QJsonObject responce, MainInterface *maininterface)
{
    QMessageBox::information(maininterface,"Tip","登录成功",QMessageBox::Yes);
    emit maininterface->ReginSuccess();      // 发送登录成功信号
}

// 登录失败
void REGISERROE::MFHandle(QJsonObject responce, MainInterface *maininterface)
{
    QMessageBox::information(maininterface,"Tip","登录失败",QMessageBox::Ok);
}

// 简单工厂
MFHandleServerptr GetHandlePtr(const int &type)
{
    qDebug()<<"GetHandlePtr type:"<<type;

    if(type == REGIS_SUCCESS)   // 登录成功
    {
        return std::make_shared<REGISSUCCESS>();
    }
    if(type == REGIS_ERROR)     // 登录失败
    {
        return std::make_shared<REGISERROE>();
    }

    return nullptr;     // 处理未知类型
}
